package leetcode_1100;

import helpclass.TreeNode;

public class MaximumDifferenceBetweenNodeAndAncestor_1026 {
	int max = 0;
	public int maxAncestorDiff(TreeNode root) {
        help(root);
        return max;
    }
	
	public int[] help(TreeNode root) {
		if(root.left == null && root.right == null) {
			return new int[] {root.val,root.val};
		}
		int [] res = new int[] {Integer.MAX_VALUE,Integer.MIN_VALUE};
		if(root.left != null) {
			int[] left = help(root.left);
			res[0] = Math.min(res[0], left[0]);
			res[1] = Math.max(res[1], left[1]);
		}
		if(root.right != null) {
			int[] right = help(root.right);
			res[0] = Math.min(res[0], right[0]);
			res[1] = Math.max(res[1], right[1]);
		}
		res[0] = Math.min(root.val, res[0]);
		res[1] = Math.max(root.val, res[1]);
		this.max =Math.max(max, 
				Math.max( Math.abs(root.val-res[0]),  Math.abs(root.val-res[1])));
		return res;
	}
}
